package com.xiaren.ui.edit;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;
import java.util.List;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTextPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.*;

import com.xiaren.bean.FileBean;
import com.xiaren.bean.SelectText;
import com.xiaren.common.IConstant;
import com.xiaren.common.ImageManager;
import com.xiaren.common.ObjectConstant;
import com.xiaren.ui.dialog.SearchDialog;
import com.xiaren.ui.tree.JTreeNode;

/**
 * @主页 http://www.leaf123.cn/
 * @邮箱 xia5523@qq.com
 */
public class TextFile extends FileEdit implements KeyListener, DocumentListener {
	// 核心，文本
	public JTextPane textPane = new JTextPane();
	// 用于文本的文档事件管理
	public UndoFunction uf = null;

	public TextFile(JTreeNode treeNote) {
		super(treeNote);
		textPane.setFont(new Font("微软雅黑",Font.PLAIN,14));
		this.getViewport().add(textPane);
		this.initEdit();
	}

	/**
	 * 为编辑选项卡添加选项
	 */
	public void initEdit() {
		for (int i = 0; i < ObjectConstant.mainEdit.getTabCount(); i++) {
			if (((FileEdit) ObjectConstant.mainEdit.getComponent(i)).id == this.id) {
				ObjectConstant.mainEdit.setSelectedComponent(this);

				return;
			}
		}
		readMySelf();
	}

	@Override
	public void keyTyped(KeyEvent e) {

	}

	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode() == KeyEvent.VK_S && e.isControlDown()) {
			this.saveMySelf();
		} else if ((e.getKeyCode() == KeyEvent.VK_LEFT && e.isAltDown()) || (e.getKeyCode() == KeyEvent.VK_Z && e.isControlDown())) {	// alt+left 或 ctrl+z
			if (uf.um.canUndo()) {
				uf.um.undo();// 撤销
			}
		} else if (e.getKeyCode() == KeyEvent.VK_RIGHT && e.isAltDown()) {
			if (uf.um.canRedo()) {// 如果能恢复的话
				uf.um.redo();// 恢复
			}
		} else if (e.getKeyCode() == KeyEvent.VK_F && e.isControlDown()) {
			SearchDialog.createFindWindow(
					new SelectText(this.textPane.getSelectedText(),
							this.textPane.getSelectionStart(), this.textPane
							.getSelectionEnd()), this);
		} else if (e.getKeyCode() == KeyEvent.VK_V && e.isControlDown()) {
			try {
				Image image = ImageManager.getImageFromClipboard();
				if (image == null) {// 如果不是图片，直接返回
					return;
				}
				this.textPane.insertIcon(new ImageIcon(image));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} else if (e.getKeyCode() == KeyEvent.VK_D && e.isControlDown()) {		// 获取选中的文字
			this.textPane.getSelectedText();

		}
	}

	/**
	 * 改变编辑
	 */
	private void updateText() {
		if (ifMaxFrame) {
			isSave = false;
			return ;
		} else {
			if (isSave) {
				isSave = false;
				int selectIndex = ObjectConstant.mainEdit.indexOfComponent(this);
				String newtitle = ObjectConstant.mainEdit.getTitleAt(selectIndex)
						+ " *";
				ObjectConstant.mainEdit.setTitleAt(selectIndex, newtitle);
			}
		}


	}

	@Override
	public void insertUpdate(DocumentEvent e) {
		updateText();
	}

	@Override
	public void removeUpdate(DocumentEvent e) {
		updateText();
	}

	@Override
	public void changedUpdate(DocumentEvent e) {

		updateText();
	}

	@Override
	public void keyReleased(KeyEvent e) {

	}

	@Override
	public String getFileContent() {
		return this.textPane.getText();
	}

	@Override
	public void writeFileContent(String content) {
		this.textPane.setText(content);
	}

	@Override
	public String getType() {
		return null;
	}

	public void saveMySelf() {
		if (!this.isSave) {// 如果没有保存，就保存一下

			this.textPane.getDocument().removeDocumentListener(this);
			// 保存文件信息
			FileBean fileBean = new FileBean(this.treeNote.treeNodeId,  this.textPane);
			ObjectConstant.mainFrame.baseDao.save(fileBean);

			this.isSave = true;
			int selectIndex = ObjectConstant.mainEdit
					.indexOfComponent(this);
			String oldTitle = ObjectConstant.mainEdit
					.getTitleAt(selectIndex);

			String newTitle = oldTitle.substring(0, oldTitle.length() - 2);
			ObjectConstant.mainEdit.setTitleAt(selectIndex, newTitle);

			this.textPane.getDocument().addDocumentListener(this);

		}
	}

	@Override
	public void readMySelf() {
		ObjectConstant.mainFrame.baseDao.getJTreeNodeById(this.treeNote.treeNodeId + "", this.textPane);
		ObjectConstant.mainEdit.add(this, fileName);
		ObjectConstant.mainEdit.setSelectedComponent(this);
		textPane.getDocument().addDocumentListener(this);
		uf = new UndoFunction(this);
		textPane.addKeyListener(this);
	}

	@Override
	public Object getTypeFile() {
		return this.textPane;
	}

	@Override
	public void setSelectFile(SelectText selectText) {
		System.out.println("setSelectFile");
		this.textPane.setSelectionStart(selectText.getBegin());
		this.textPane.setSelectionEnd(selectText.getEnd());
		System.out.println(this.textPane.getText().substring(selectText.getBegin(),selectText.getEnd()));
	}

	@Override
	public SelectText getSelectFile() {
		System.out.println("getSelectFile");
		return new SelectText(this.textPane.getSelectedText(),
				this.textPane.getSelectionStart(),
				this.textPane.getSelectionEnd());
	}

	public List<ImageIcon> getListDocumentImage(){
		List<ImageIcon> list = new ArrayList<ImageIcon>();
		for(int i=0;i<this.textPane.getStyledDocument().getRootElements()[0].getElementCount();i++){
			javax.swing.text.Element root = this.textPane.getStyledDocument().getRootElements()[0].getElement(i);
			for(int j=0;j<root.getElementCount();j++){
				ImageIcon icon = (ImageIcon) StyleConstants.getIcon(root.getElement(j).getAttributes());
				if(icon!=null){
					list.add(icon);
				}
			}
		}
		return list;
	}

	public Image getDocumentImage(){
		List<ImageIcon> imageList = getListDocumentImage();
		if(!imageList.isEmpty()){
			int index = ObjectConstant.imageCopyParams++ % imageList.size();
			Image image = imageList.get(index).getImage();
			return image;
		}
		return null;
	}

}
